package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.text.TextUtils
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.cl.picture_selector.ImagePicker
import com.google.gson.reflect.TypeToken
import com.jt.assistant.R
import com.jt.assistant.adapter.CarDialogListAdapter
import com.jt.assistant.adapter.JDDialogListAdapter
import com.jt.assistant.adapter.PicAdapter
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.bean.HandingFeeWaybillList
import com.jt.assistant.bean.Param
import com.jt.assistant.bean.WaybillCityBean
import com.jt.assistant.bean.Waybills
import com.jt.assistant.custom_view.ItemEdit
import com.jt.assistant.utils.BasisTimesUtils
import com.jt.assistant.utils.GlideLoader
import com.jt.assistant.viewmodel.HomeViewModel
import com.orhanobut.logger.Logger
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_car_cost.*
import kotlinx.android.synthetic.main.activity_car_cost.bt_commit
import kotlinx.android.synthetic.main.activity_car_cost.ie_remark
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.util.*

/**
 * 装卸费上报
 */
class CarCostActivity : BaseActivity<HomeViewModel>() {
    private val mAdapter by lazy {
        PicAdapter(
            ArrayList<String>()
        )
    }

    private val maxPicCount = 10//最大图片选择数量
    private var mMoney = ArrayList<Double>()
    private var mHandingType = "1" //3为计划卸货

    override fun layoutId(): Int = R.layout.activity_car_cost

    override fun initView(savedInstanceState: Bundle?) {
        ie_handingV.mEdit.inputType =
            InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
        with(rv_carCost) {
            layoutManager = GridLayoutManager(context, 3)
            canScrollVertically(0)
            adapter = mAdapter
            mAdapter.data.add("")
            mAdapter.notifyDataSetChanged()
        }

    }

    override fun initData() {
        ie_handingType.mData.add("装车")
        ie_handingType.mData.add("卸车")
        ie_handingType.setEditText("装车")

        ie_carType.setEditText(if (intent.getStringExtra("Type") == "2") "退货车辆" else "送货车辆")
        ie_time.mEdit.setText(BasisTimesUtils.getDeviceTimeOfYMD())

        //自送装卸费上报
        if (intent.getStringExtra("Type") == "3") {
            ie_handingType.mEdit.setText("卸货")
            mHandingType = "2"
        }

        val params = Param::class.java.newInstance()
        params.code = "load_car_charge_list"
        viewModel.getDic(params)
    }

    override fun initListener() {
        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (mAdapter.data[position].isEmpty()) {
                ImagePicker.getInstance()
                    .setTitle("标题") //设置标题
                    .showCamera(true) //设置是否显示拍照按钮
                    .showImage(true) //设置是否展示图片
                    .showVideo(true) //设置是否展示视频
                    .showLoading(true, "请稍后...")
                    .setMaxCount(maxPicCount - mAdapter.itemCount + 1) //设置最大选择图片数目(默认为1，单选)
                    .setSingleType(true) //设置图片视频不能同时选择
                    .setImageLoader(GlideLoader()) //设置自定义图片加载器
                    .start(
                        this@CarCostActivity,
                        GlobalConfig.REQUEST_SELECT_IMAGES_CODE
                    ) //REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode
            } else {//预览图
                startActivityForResult(Intent(this@CarCostActivity, PreActivity::class.java).apply {
                    putExtra("IMAGEPATH", GsonUtils.toJson(mAdapter.data))
                    putExtra("POSITION", position)
                }, GlobalConfig.PIC_REQUEST)
            }
        }


        ie_handingMoney.mEdit.setOnClickListener {
            ie_handingMoney.showListDialog("请选择单方费用", this)
        }


        ie_handingType.mEdit.setOnClickListener {
            ie_handingType.showListDialog("请选择装车卸车", this)
        }

        ie_handingType.setOnItemClickListener(object : ItemEdit.OnClickLister {
            override fun onItemClick(position: Int) {
                mHandingType = (position + 1).toString()
            }
        })

        ie_time.mEdit.setOnClickListener {
            showYearMonthDayPicker()
        }


        ie_jdSelect.mEdit.setOnClickListener {
            val params = Param::class.java.newInstance()
            params.type = intent.getStringExtra("Type").toString()
            params.id = intent.getStringExtra("Id").toString()
            params.handingType = mHandingType
            viewModel.waybillDetail(params)
        }


        bt_commit.setOnClickListener {
//            ToastUtils.showShort(mMoney[ie_handingMoney.mCurrentPosition].toString())

            if (ie_handingV.mEdit.text.isEmpty()) {
                ToastUtils.showShort("请输入装卸体积")
                return@setOnClickListener
            }
            if (ie_handingMen.mEdit.text.isEmpty()) {
                ToastUtils.showShort("请输入装卸人员")
                return@setOnClickListener
            }

            if (mAdapter.data.size == 1) {
                ToastUtils.showShort("请选择图片")
                return@setOnClickListener
            }

            val params = Param::class.java.newInstance()
            params.type = intent.getStringExtra("Type").toString()
            params.dispatchCarId = intent.getStringExtra("Id").toString()
            log(ie_handingV.mEdit.text.toString().toDouble())

            params.handingFee = String.format(
                "%.2f",
                (ie_handingV.mEdit.text.toString().toDouble()
                        * (mMoney[ie_handingMoney.mCurrentPosition]))
            )
            params.handingMan = ie_handingMen.mEdit.text.toString()
            params.handingType = mHandingType
            params.applyTime = ie_time.mEdit.text.toString()
            params.remark = ie_remark.mEdit.text.toString()

            params.volume = ie_handingV.mEdit.text.toString()
            params.price = mMoney[ie_handingMoney.mCurrentPosition].toString()
            params.handingFeeWaybillList = mJdList
            log(params.handingFee)
            viewModel.addHandingFee(params, mAdapter.data)
        }

        viewModel.mGetDic.observe(this, { result ->
            if (result.isSuccess()) {
                result.data.forEach {
                    mMoney.add(it.dictValue.toDouble())
                }
                mMoney.sort()
                mMoney.forEach {
                    ie_handingMoney.mData.add(it.toString().replace(".0", "") + "元/方")
                }
                ie_handingMoney.mEdit.setText(ie_handingMoney.mData[0])
            }
        })



        viewModel.mAddHandingFee.observe(this, {
            if (it.isSuccess()) {
                speakString("上报成功")
                finish()
            }
        })

        viewModel.mWaybillDetail.observe(this, {
            if (it.isSuccess()) {
                showJDDialog("请选择单号", it.data)
            }
        })


    }


    private fun showYearMonthDayPicker() {
        val calendar = Calendar.getInstance()
        BasisTimesUtils.showDatePickerDialog(this@CarCostActivity,
            BasisTimesUtils.THEME_HOLO_DARK,
            "请选择年月日",
            calendar[Calendar.YEAR],
            calendar[Calendar.MONTH] + 1,
            calendar[Calendar.DATE],
            object : BasisTimesUtils.OnDatePickerListener {
                @SuppressLint("SetTextI18n")
                override fun onConfirm(year: Int, month: Int, dayOfMonth: Int) {
                    ie_time.mEdit.setText(
                        "$year-" + String.format(
                            "%02d",
                            month
                        ) + "-" + String.format("%02d", dayOfMonth)
                    )
                    showTimePick()
                }

                override fun onCancel() {}
            })
    }


    private fun showTimePick() {
        BasisTimesUtils.showTimerPickerDialog(this@CarCostActivity, "请选择时分",
            Calendar.getInstance()[Calendar.HOUR_OF_DAY],
            Calendar.getInstance()[Calendar.MINUTE], true,
            object : BasisTimesUtils.OnTimerPickerListener {
                @SuppressLint("SetTextI18n")
                override fun onConfirm(hourOfDay: Int, minute: Int) {
                    ie_time.mEdit.setText(
                        ie_time.mEdit.text.toString() + String.format(
                            " %02d",
                            hourOfDay
                        ) + ":" + String.format("%02d", minute) + ":00"
                    )
                }

                override fun onCancel() {
                    ToastUtils.showShort("请选择时间")
                    showTimePick()
                }
            })
    }


    private fun imagePick(mImagePaths: ArrayList<String>?) {
        Luban.with(this)
            .load<String>(mImagePaths)
            .ignoreBy(100)
//            .setTargetDir(ImageUtil.getPath())
            .setFocusAlpha(false)
            .filter { path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")) }
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {}

                @SuppressLint("SetTextI18n")
                override fun onSuccess(file: File) {
                    Logger.e(file.absolutePath)
                    mAdapter.data.add(0, file.absolutePath)
                    mAdapter.notifyDataSetChanged()
                    if ((mAdapter.data.size - 1) == maxPicCount) {
                        mAdapter.data.remove("")
                        mAdapter.notifyDataSetChanged()
                    }
                }

                override fun onError(e: Throwable) {

                }
            }).launch()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == GlobalConfig.REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            imagePick(data!!.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES))
        }

        if (requestCode == GlobalConfig.PIC_REQUEST && resultCode == RESULT_OK) {
            val picList = GsonUtils.fromJson<ArrayList<String>>(
                data!!.getStringExtra(GlobalConfig.PIC_RESULT),
                object : TypeToken<ArrayList<String>>() {}.type
            )
            imagePickPre(picList)
        }
    }

    private fun imagePickPre(picList: ArrayList<String>?) {
        mAdapter.data.clear()
        if (picList!!.isNotEmpty()) {
            mAdapter.data.addAll(picList)
        }
        mAdapter.data.add("")
        if ((mAdapter.data.size - 1) == maxPicCount) {
            mAdapter.data.remove("")
        }
        mAdapter.notifyDataSetChanged()
    }


    var mJdTotalNum = ""
    var mJdList = ArrayList<Waybills>()


    @SuppressLint("SetTextI18n")
    private fun showJDDialog(title: String, listData: List<HandingFeeWaybillList>) {
        val dialog = MaterialDialog(this).show {
            title(text = title)
            customView(
                R.layout.layout_dialog_jd_list,
                scrollable = false,
                horizontalPadding = false
            )
            lifecycleOwner(this@CarCostActivity)
        }
        // Setup custom view content
        val customView = dialog.getCustomView()
        val rvDialog: RecyclerView = customView.findViewById(R.id.rv_dialog)
        val check: ImageView = customView.findViewById(R.id.jd_check_iv)
        val cartonNum: TextView = customView.findViewById(R.id.carton_num_tv)
        val oneKey: RelativeLayout = customView.findViewById(R.id.rl_oneKey)
        val cancel: TextView = customView.findViewById(R.id.tv_cancle)
        val commit: TextView = customView.findViewById(R.id.tv_commit)
        val listAdapter = CarDialogListAdapter(ArrayList<HandingFeeWaybillList>())
        check.load(R.mipmap.icon_uncheck)

        cancel.setOnClickListener { dialog.dismiss() }
        commit.setOnClickListener {
            //运单号List  总箱码
            mJdList.clear()
            mJdTotalNum = cartonNum.text.toString()

            listAdapter.data.forEach {
                if (it.isChoose)
                    mJdList.add(Waybills(it.channelOrderNo, it.volume, it.weight, it.isChoose))
            }

            if (mJdList.isEmpty())
                ie_jdSelect.setEditText("")
            else
                ie_jdSelect.setEditText("已选择(${getTotleNum(listAdapter.data)}m³)")

            dialog.dismiss()

        }

        oneKey.setOnClickListener {
            var isChoose = isAllChoose(listAdapter.data)

            listAdapter.data.forEach {
                it.isChoose = !isChoose
            }
            listAdapter.notifyDataSetChanged()
            cartonNum.text = getTotleNum(listAdapter.data).toString()+"m³"

            isChoose = isAllChoose(listAdapter.data)
            if (isChoose) check.load(R.mipmap.icon_checked) else check.load(R.mipmap.icon_uncheck)
        }

        with(rvDialog) {
            layoutManager = LinearLayoutManager(context)
            adapter = listAdapter
            listAdapter.data.addAll(listData)
            listAdapter.notifyDataSetChanged()
        }

        listAdapter.setOnItemClickListener { adapter, view, position ->
            listAdapter.data[position].isChoose = !listAdapter.data[position].isChoose
            listAdapter.notifyDataSetChanged()

            cartonNum.text = getTotleNum(listAdapter.data).toString()
            val isChoose = isAllChoose(listAdapter.data)
            if (isChoose) check.load(R.mipmap.icon_checked) else check.load(R.mipmap.icon_uncheck)
        }
    }

    private fun getTotleNum(data: MutableList<HandingFeeWaybillList>): Double {
        var totalNum = 0.0
        data.forEach {
            if (it.isChoose)
                totalNum += it.volume
        }
        return String.format(
            "%.2f",
            totalNum
        ).toDouble()
    }

    private fun isAllChoose(data: MutableList<HandingFeeWaybillList>): Boolean {
        data.forEach {
            if (!it.isChoose) return false
        }
        return true
    }


}